<%@ page language="java" import="java.lang.*"  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
%>
<div id = "produce_edit_page" class="row-fluid" style="border:0px;">
    <form id="baseInfor" class="form-horizontal" method="post" target="_ifr" style="border-bottom: solid 2px #3b73af;">
        <!-- 隐藏的入库单主键 -->
        <input type="hidden" id="id" name="id" value="${poo.id }">
            <div class="row" style="margin:0;padding:0;">
                <div class="control-group span6" style="display: inline">
                    <label class="control-label" for="orderCode" >订单编号：</label>
                    <div class="controls">
                        <div class="required" >
                            <input type="text" id="orderCode" class="span10" name="orderCode" readonly value="${poo.orderCode }"  placeholder="后台自动生成" />
                        </div>
                    </div>
                </div>
                <div class="control-group span6" style="display: inline">
                    <label class="control-label" for="orderPlanTime1">计划时间：</label>
                    <div class="controls">
                        <div class="required spa10">
                            <input class="form-control date-picker" id="orderPlanTime1" name="orderPlanTime1" type="text" value="${fn:substring(poo.orderPlanTime1,0,19)}" placeholder="计划时间" class="span8" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="row" style="margin:0;padding:0;">
                <div class="control-group span6">
                    <label class="control-label" for="saleId">销售单号：</label>
                    <div class="controls">
                        <div class="required" style=" float: none !important;">
                            <input type="hidden" id="saleId" name="saleId" value="${poo.saleId }">
                            <select class="mySelect2 span10" id="instorageTypeSelect" name="instorageTypeSelect" data-placeholder="请销售单号" style="margin-left:0px;">
                                <option value=""></option>
                                <c:forEach items="${goodsList}" var="in">
                                    <option value="${in.id}" <c:if test="${poo.saleId==in.id }">selected="selected"</c:if>>
                                            ${in.saleNo}
                                    </option>
                                </c:forEach>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        <div style="margin-bottom:5px;margin-left:10px;">
            <span class="btn btn-info" id="formSave">
		       <i class="ace-icon fa fa-check bigger-110"></i>保存
            </span>
        </div>
    </form>
    <!-- 入库单搜索div -->
    <div id="materialDiv" style="margin:10px;">
        <!-- 下拉框 -->
        <label class="inline" for="materialInfor">产品：</label>
        <input type="text" id = "materialInfor" name="materialInfor" style="width:350px;margin-right:10px;" />
        <button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
            <i class="icon-plus" style="margin-right:6px;"></i>添加
        </button>
    </div>
    <!-- 表格div -->
    <div id="grid-div-c" style="width:100%;margin:0px auto;">
        <!-- 	表格工具栏 -->
        <div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
            <div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
        <!-- 入库单信息表格 -->
        <table id="grid-table-c" style="width:100%;height:100%;"></table>
        <!-- 表格分页栏 -->
        <div id="grid-pager-c"></div>
    </div>
</div>
<iframe src="about:blank" name="_ifr" height="0" class="hidden"></iframe>
<script type="text/javascript" src="<%=path%>/static/js/techbloom/wms/ordermanage/produceorder/produceorder_detail.js"></script>
<script type="text/javascript">
    var context_path = '<%=path%>';
    var oriData;      //表格数据
    var _grid;        //表格对象
    var selectData = 0;   //存放物料选择框中的值
    var selectParam = "";  //存放之前的查询条件

    //清空物料多选框中的值
    function removeChoice(){
        $("#s2id_materialInfor .select2-choices").children(".select2-search-choice").remove();
        $("#materialInfor").select2("val","");
        selectData = 0;

    }

    if ($("#baseInfor #instorageTypeSelect").val() == "WMS_INSTORAGE_YK") {
        $("#baseInfor area-arrow").show(200);
        $("#baseInfor #s2id_inWarehouseId").show(300);
        $("#baseInfor #supplierLable").removeClass("inline");
        $("#baseInfor #supplierLable").addClass("hide");
    } else {
        $("#baseInfor #s2id_inWarehouseId").hide(300);
        $("#baseInfor #area-arrow").hide(200);
        $("#baseInfor #supplierLable").addClass("inline");
        $("#baseInfor #supplierLable").removeClass("hide");
    }

    $("#materialInfor").select2({
        placeholder : "请选择产品",//文本框的提示信息
        minimumInputLength : 0, //至少输入n个字符，才去加载数据
        allowClear : true, //是否允许用户清除文本信息
        multiple: true,
        closeOnSelect:false,
        ajax : {
            url : context_path + "/produceOrder/getmaterialList?saleId="+$("#baseInfor #saleId").val(),
            dataType : "json",
            delay : 250,
            data : function(term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                selectParam = term;
                return {
                    queryString : term, //联动查询的字符
                    pageSize : 15, //一次性加载的数据条数
                    pageNo : pageNo, //页码
                    time : new Date()
                    //测试
                }
            },
            results : function(data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results : res,
                        more : more
                    };
                } else {
                    return {
                        results : {
                            "id" : "0",
                            "text" : "没有更多结果"
                        }
                    };
                }

            },
            cache : true
        }
    });

    $("#materialInfor").on("change",function(e){
        var datas=$("#materialInfor").select2("val");
        selectData = datas;
        var selectSize = datas.length;
        if(selectSize>1){
            var $tags = $("#s2id_materialInfor .select2-choices");   //
            //$("#s2id_materialInfor").html(selectSize+"个被选中");
            var $choicelist = $tags.find(".select2-search-choice");
            var $clonedChoice = $choicelist[0];
            $tags.children(".select2-search-choice").remove();
            $tags.prepend($clonedChoice);

            $tags.find(".select2-search-choice").find("div").html(selectSize+"个被选中");
            $tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
            $tags.find(".select2-search-choice").find("a").attr("href","#");
            $tags.find(".select2-search-choice").find("a").attr("onclick","removeChoice();");
        }
        //执行select的查询方法
        $("#materialInfor").select2("search",selectParam);
    });

    $(".date-picker").datetimepicker({format: "YYYY-MM-DD HH:mm:ss",useMinutes:true,useSeconds:true});

    $(".mySelect2").select2();

    $("#baseInfor #instorageTypeSelect").change(function(){
        $("#baseInfor #saleId").val($("#baseInfor #instorageTypeSelect").val());
    });

    $("#baseInfor").validate({
        ignore: "",
        rules: {
            "orderPlanTime1":{
                required: true,
            },
            "instorageTypeSelect":{
                required: true,
            }
        },
        messages:{
            "orderPlanTime1":{
                required: "请输入计划时间",
            },
            "instorageTypeSelect":{
                required: "请选择销售订单",
            }
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents(".control-group").addClass("error");
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents(".control-group").removeClass("error");
        }
    })
    //单据保存按钮点击事件
    $("#formSave").click(function(e){
        if($("#baseInfor").valid()){
            var formdata = $("#baseInfor").serialize();
            saveFormInfo(formdata);
        }
    });

    //工具栏
    $("#__toolbar__-c").iToolBar({
        id:"__tb__01",
        items:[
            {label:"删除", onclick:delDetail},
            /*{label:"生产出库计划", onclick:outPlan}*/
        ]
    });

    //初始化表格
    _grid = $("#grid-table-c").jqGrid({
        url : context_path + "/produceOrder/getDetail?pId="+$("#baseInfor #id").val(),
        datatype : "json",
        colNames : [ "物料主键","产品编号","产品名称","产品数量"],
        colModel : [
            {name : "id",index : "id",width : 55,hidden:true},
            {name : "materialNo",width : 30},
            {name : "materialName",width : 30},
            {name : "amount",width : 20,editable: true,editrules: { custom : true,custom_func : myamountcheck }}
        ],
        rowNum : 20,
        rowList : [ 10, 20, 30 ],
        pager : "#grid-pager-c",
        sortname : "pod.id",
        sortorder : "asc",
        altRows: true,
        viewrecords : true,
        autowidth:true,
        multiselect:true,
        multiboxonly: true,
        loadComplete : function(data){
            var table = this;
            setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
            oriData = data;
            $(window).triggerHandler('resize.jqGrid');
        },
        emptyrecords: "没有相关记录",
        loadtext: "加载中...",
        pgtext : "页码 {0} / {1}页",
        recordtext: "显示 {0} - {1}共{2}条数据",
        cellEdit: true,
        cellurl: context_path + "/produceOrder/saveAmount",
        /*cellsubmit : "clientArray",*/
    });
    //在分页工具栏中添加按钮
    $("#grid-table-c").navGrid("#grid-pager-c",{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd('#grid-pager-c',{
            caption:"",
            buttonicon:"ace-icon fa fa-refresh green",
            onClickButton: function(){
                $("#grid-table-c").jqGrid("setGridParam",
                    {
                        postData: {instoreID:$("#baseInfor #id").val(),queryJsonString:""} //发送数据  :选中的节点
                    }
                ).trigger("reloadGrid");
            }
        });

    $(window).on("resize.jqGrid", function () {
        $("#grid-table-c").jqGrid("setGridWidth", $("#grid-div-c").width() - 3 );
        var height = $(".layui-layer-title",_grid.parents(".layui-layer")).height()+
                     $("#baseInfor").outerHeight(true)+
                     $("#grid-pager-c").outerHeight(true)+
                     $("#materialDiv").outerHeight(true)+
                     $("#fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
                     $("#gview_grid-table-c .ui-jqgrid-hbox").outerHeight(true);
                     $("#grid-table-c").jqGrid("setGridHeight", _grid.parents(".layui-layer").height()-height );
    });

    if($("#id").val()!=""){
        reloadDetailTableList();   //重新加载详情列表
    }
    //添加入库单详情
    function addDetail(){
        if($("#baseInfor #id").val()==-1){
            layer.alert("请先保存表单信息！");
            return;
        }
        if(selectData!=0){
            //将选中的物料添加到数据库中
            $.ajax({
                type:"POST",
                url:context_path + "/produceOrder/saveDetail",
                data:{pId:$("#baseInfor #id").val(),materialId:selectData.toString()},
                dataType:"json",
                success:function(data){
                    removeChoice();   //清空下拉框中的值
                    if(data.result!=null){
                        if(data.msg){
                            layer.alert(data.msg+"已经存在,不能重复添加");
                        }else {
                            layer.alert("添加成功");
                        }
                        //重新加载详情表格
                        $("#grid-table-c").jqGrid("setGridParam",
                            {
                                postData: {pId:$("#baseInfor #id").val()} //发送数据  :选中的节点
                            }
                        ).trigger("reloadGrid");
                    }else{
                        layer.alert("添加失败");
                    }
                }
            });
        }else{
            layer.alert("请选择物料！");
        }
    }
    //修改表单的提交状态
    function formSubmitBtn(){
        childDiv = layer.confirm("确认提交？",
            function(){
                //后台修改表单状态为提交
                $.ajax({
                    type:"POST",
                    url:context_path+"/instorage/setInstoreState",
                    data:{instoreID:$('#baseInfor #id').val()},
                    dataType:"json",
                    success:function(data){
                        if(data.msg!=""){
                            layer.alert(data.msg);
                            return;
                        }
                        if(Boolean(data.result)){
                            //修改成功
                            //关闭当前窗口
                            layer.closeAll();
                            //弹出提示，
                            layer.msg("单据提交成功",{icon:1,time:1200});
                            //showTipMsg("单据提交成功",1200);
                            //刷新父窗口的表格数据
                            gridReload();
                        }
                    }
                });
            },
            function(){

            });
    }
    function myamountcheck(value, colname) {
        var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
        if (!reg.test(value)) {
            layer.alert("非法的数量！(注：可以有两位小数的正实数)");
            return [ false,  ""];
        }else {
            return [ true, "" ];
        }
    }
    //关闭当前窗口
    function closeWindowBtn(){
        layer.closeAll();
    }
</script>